﻿using System;
using System.Web;
using System.Web.Mvc;
using Microsoft.Web.Helpers;
using FlickrNet;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web.Mvc.Html;
using System.Linq.Expressions;
using System.IO;
using System.Text;
using System.Xml;

namespace SisocanaFrontEnd.Helpers
{
    public static class HtmlHelpers
    {
        public static String SiteImages(this HtmlHelper html, int idSitio)
        {
            string folderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content\\images\\Site\\"+idSitio);
            if (!Directory.Exists(folderPath))
                return "";      
            
            DirectoryInfo imageFolder = new DirectoryInfo(folderPath);
            FileInfo[] files = imageFolder.GetFiles();

            StringBuilder sb = new StringBuilder();
            UrlHelper urlHelper = new UrlHelper(html.ViewContext.HttpContext.Request.RequestContext);
            foreach (var fileInfo in files)
                sb.AppendLine(String.Format("<img src='{0}Content/images/Site/{1}/{2}' alt='{2}'/>", urlHelper.Action(""), idSitio, fileInfo.Name));

            return sb.ToString();
        }

        public static string ACJsonInit(this HtmlHelper helper)
        {
            string res = "<script src=\"" + VirtualPathUtility.ToAbsolute("~/Content/Autocomplete/jquery.autocomplete.js") + "\"></script> \n";
            res += "<link href=\"" + VirtualPathUtility.ToAbsolute("~/Content/Autocomplete/jquery.autocomplete.css") + "\" rel=\"stylesheet\" type=\"text/css\"/> ";
            return res;
        }
        public static string ACJson(this HtmlHelper helper, string idInput,string idForm)
        {
            UrlHelper urlHelper = new UrlHelper(helper.ViewContext.HttpContext.Request.RequestContext);
            string urlRecurso = urlHelper.Action("ACJson", "Util");
            
            string res = "<script type=\"text/javascript\">";
            res += "$(document).ready(function(){ \n";
           
            //selecciono el form y cambio el action.
            res += "$(\"#" + idForm + "\").attr(\"action\", \""+urlRecurso+"R\");";
            res += "$(\"#" + idInput + "\").result(log);";
            res += "function log(event, data, formatted) {";
            res +=    "$(\"#id\").val(data.id);";
            res +=    "$(\"#idsitio\").val(data.idsitio);}";
     
    
            res += "$(\"#" + idInput + "\").autocomplete('" + urlRecurso + "', \n";
            res += "{ dataType: 'json',parse: function(data) { \n";
            res += "var rows = new Array(); for (var i = 0; i < data.length; i++) { \n";
            res += " rows[i] = { data: data[i], value: data[i].Name +' ' +data[i].Surname, result: data[i].Name +' '+ data[i].Surname }; \n }";
            res += " return rows; },formatItem: function(row, i, max) \n";
            res += " { return \"<img src=\" + row.ImgUrl + \" height='35px' width='35px'   />\" +' ' +row.Name +' ' + row.Surname; }, \n";           
            res += "formatResult: function(row) {return row.Name + row.Surname;},\n";            
            res += " highlight: false, multiple: false, })}); ";              
            res+= "</script> \n";

            return res;

        }

        public static String Div(this HtmlHelper helper, string divClass, MvcHtmlString content = null)
        {
            return String.Format("<div class='{0}'>{1}</div>", divClass, content);
        }

        public static String FieldFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
        {
            return String.Format("<div class='editor-label'>{0}</div><div class='editor-field'>{1}{2}</div>",                
                LabelExtensions.LabelFor(html, expression),
                InputExtensions.TextBoxFor(html, expression),
                ValidationExtensions.ValidationMessageFor(html, expression));
        }

        public static String GoogleMap(this HtmlHelper helper, string idCoordX, string idCoordY, bool useGeolocation)
        {
            return String.Format("<a id='map_{0}_show' href=\"javascript:toggle('map_{0}','{0}','{1}','{2}');\">Show map</a>" +
            "<a id='map_{0}_hide' style='display: none;' href=\"javascript:toggle('map_{0}');\">Hide map</a>" +
            "<div id='map_{0}' class='locationMap' style='display: none;'></div>", idCoordX, idCoordY, useGeolocation);
        }

        public static string FacebookIcon(this HtmlHelper helper, string faceurl)
        {
            if (faceurl == "")
                return "";

            string imgurl = VirtualPathUtility.ToAbsolute("~/Content/images/facebook.png");
            string faceurlFull = "http://www.facebook.com/" + faceurl.Trim();
            return "<a href='" + faceurlFull + "' rel='nofollow' target='_blank'><img width='36' height='36' src='" + imgurl.Trim() + "' alt='Follow on Facebook' title='Follow on Facebook'></a>";       
        }

        public static string TwitterIcon(this HtmlHelper helper, string twetturl)
        {
            if (twetturl=="")
                return "";
                
            string imgurl = VirtualPathUtility.ToAbsolute("~/Content/images/twitter.png");
            string urlFull = "http://twitter.com/" + twetturl.Trim();
            return "<a href='" + urlFull + "' rel='nofollow' target='_blank'><img width='36' height='36' src='" + imgurl.Trim() + "' alt='Follow on Twitter' title='Follow on Twitter'></a>";   
        }


        public static HtmlString TProfile(this HtmlHelper helper, string user, string largo,string ancho,string col1,string col2,string col3,string col4,string cant)
        {
            if (user == "" )
                return new HtmlString("");
            else
                return Microsoft.Web.Helpers.Twitter.Profile(user,Int32.Parse(ancho),Int32.Parse(largo),col1,col2,col3,col4,"#2667b5",Int32.Parse(cant),false,false,false,true,true,false,"all",6000);
              
        }

        public static IHtmlString TSearch(this HtmlHelper helper, string buscar, string largo, string ancho, string col1, string col2, string col3, string col4, string cant)
        {
            if (buscar == "")
                return new HtmlString("");
            else
                return Microsoft.Web.Helpers.Twitter.Search(buscar, Int32.Parse(ancho), Int32.Parse(largo),"Feed Search For" ,buscar, col1, col2, col3, col4, "#2667b5", false, true, true, true, true, true, "default", 6000);               
               

        }

        public static string WebLogo(this HtmlHelper helper, string siteId)
        {
            string url = VirtualPathUtility.ToAbsolute("~/Recursos/imagen/") + siteId;
            return "<img src='"+url+"' width='320' height='215'/>";           
        }

        public static string ImageHtml5Resources(this HtmlHelper helper, int height, int width)
        {
            int a1 = (int)(width * 0.85051);
            int a2 = (int) (height*0.85677);

           // return "<script src=\"" + VirtualPathUtility.ToAbsolute("~/Scripts/jquery-1.5.1.min.js") + "\"></script> \n"
            return "<script src=\"" + VirtualPathUtility.ToAbsolute("~/Scripts/jquery.cycle.all.js") + "\"></script> \n"
                 + "<link rel=\"stylesheet\" href=\"" + VirtualPathUtility.ToAbsolute("~/Content/Html5/imageGallery.css") + "\" type=\"text/css\" media=\"all\"> \n"
                 + "<style> \n"
                 + " .pics {  \n"
	             + "    width:  " + width.ToString() + "px; \n"
                 + "    height: " + height.ToString() + "px; \n"
                 + " } \n"
                 + " .pics img { \n"
                 + "    width:  " + a1.ToString() + "px; \n"
                 + "    height: " + a2.ToString() + "px; \n"
                 + " }\n"
                 + "</style> \n";
        }

        public static string ImageHtml5Script(this HtmlHelper helper)
        {
            return "<script type=\"text/javascript\"> \n"
                 + "    $(document).ready(function() { \n"
                 + "    $('.pics').cycle({ \n"
                 + "        timeout: 0 , \n"
                 + "        fx: 'toss', \n"
                 + "        next: '#next', \n"
                 + "        prev: '#prev' ,\n"

                 + "    });\n"
                 + "    }); \n"
                 + "</script> \n";
        }
        
        public static string ImageResources(this HtmlHelper helper, string colorHex)
        {
            if (colorHex == "")
                return "";
            else
                //return "<script src=\"" + VirtualPathUtility.ToAbsolute("~/Scripts/jquery-1.5.1.min.js") + "\"></script> \n"
                return "<script src=\"" + VirtualPathUtility.ToAbsolute("~/Scripts/galleria-1.2.3.min.js") + "\"></script> \n"
                     + "<style type=\"text/css\"> \n"
                     + "  .galleria-container { \n"
                     + "  background: " + colorHex.ToString() + "; \n"
                     + " } \n"
                     + " .galleria-thumb-nav-left:hover, .galleria-thumb-nav-right:hover { \n"
                     + "  background-color: " + colorHex.ToString() + "; \n"
                     + " } \n"
                     + "</style>\n";
        }


        public static string getImageFlickrSearch(this HtmlHelper helper, string apikey, string secret, string key, int cant)
        {
            if (apikey == "" || secret == "" || key == "" || cant == 0)
                return "";
            else
            {
                Flickr flickr = new Flickr(apikey, secret);
                PhotoSearchOptions searchOptions = new PhotoSearchOptions();
                searchOptions.Text = key.Replace(' ', '+');
                Flickr.CacheDisabled = true;
                try
                {
                    PhotoCollection photos = flickr.PhotosSearch(searchOptions);
                    string ret = "";
                    int cant2 = photos.Count;
                    for (int i = 1; i <= cant && i < cant2; i++)
                    {
                        ret += "<img src=\"" + photos.ElementAt(i).SmallUrl + "\"alt=\"" + photos.ElementAt(i).Description + "\" /> \n";
                    }
                    return ret;
                }
                catch (Exception e)
                {
                }
                return "";
            }
        }


        public static string ImageScript(this HtmlHelper helper, int height, int width)
        {
            if (height <= 0 || width <= 0)
                return "<p> The Images will render here! </p>";
            else
                return "<script>\n"
                     + "//$(document).ready(function() { \n"
                     + "   Galleria.loadTheme(\"" + VirtualPathUtility.ToAbsolute("~/Content/Galleria/galleria.classic.min.js") + "\"); \n"
                     + "   $(\"#gallery\").galleria({ \n"
                     + "         height: " + height.ToString() + ", \n"
                     + "          width: " + width.ToString() + ", \n"
                     + "          image_crop: true, \n"
                     + "          transition: 'fade' \n" 
                     + "  }); \n"
                     + " // }); \n"
                     + "</script>\n";
        }

        public static string VideoResources(this HtmlHelper helper, string key)
        {
            if (key == "")
                return "";
            else
                return "<script src=\"http://www.google.com/uds/api?file=uds.js&v=1.0&key=" + key + "\" type=\"text/javascript\"></script>"
                     + "<script src=\"" + VirtualPathUtility.ToAbsolute("~/Scripts/gsvideosearch.js") + "\"></script> \n"
                     + "<link href=\"" + VirtualPathUtility.ToAbsolute("~/Content/Video/gsvideosearch.css") + "\" rel=\"stylesheet\" type=\"text/css\"/> "
                     + "<style type=\"text/css\"> \n "
                     + " #videosc { \n"
                     + "    width : 300px; \n"
                     + "    margin-left: 0px; \n"
                     + "    padding: 4px; \n"
                     + "    border : 1px  #FEFEFE; \n"
                     + "  } "
                     + "</style> \n ";
        }

        public static string VideoScript(this HtmlHelper helper, string word, Boolean isLarger)
        {
            if (word == "")
                return "<p> The Video will render here! </p>";
            else
                return "<script type=\"text/javascript\"> \n"
                    +  "function OnLoad() { \n"
                    +  "    var defaultTags = [{ query : \"" + word + "\" } ]; \n"
                    + "    var options = {largeResultSet  : " + isLarger.ToString().ToLower() + " } \n " 
                    +  "    new GSvideoSearchControl( \n"
                    +  "            document.getElementById(\"videosc\"),  \n"
                    +  "            defaultTags,                           \n" 
                    +  "            null, \n"
                    +  "            null, \n"
                    +  "            options \n "
                    +  "            ); \n "
                    +  "    $(\".gsc-search-box\").hide(); \n"
                    + "     $(\".footerBox_gsvsc\").hide(); \n"
                    +  "    $(\".tagStackBox_gsvsc\").hide(); \n"
                    +  "} \n"
                    +  "GSearch.setOnLoadCallback(OnLoad); \n"
                    +  "</script> \n";
        }

        public static string VideoSearch(this HtmlHelper helper, string key, int cant, int height, int width)
        {
            using (XmlReader reader = XmlReader.Create("http://gdata.youtube.com/feeds/api/videos?vq=" + key))
            {
                string ret = "";
                string codigo = "";
                int aux = 0;
                ret = ret + "<script type=\"text/javascript\" src=\"" + VirtualPathUtility.ToAbsolute("~/Scripts/carrusel.js") + "\"></script>	 \n"
                          + "<style> \n"
                          + "	#container{ \n"
                          + "   	/*border:1px solid magenta;*/ \n"
                          + "       width:" + width.ToString() + "px; \n"
                          + "		height:" + Convert.ToInt32((height * 0.4)).ToString() + "px; \n"
                          + "		margin-left:25px; \n"
                          + "       margin-bottom: 60px; \n"
                          + "	} \n"
                          + "	#container img, #container .item{ \n"
                          + "  		width:100%; \n"
                          + " 		height:100%; \n"
                          + "		-webkit-border-radius: 10px; \n"
                          + "		-moz-border-radius: 10px; \n"
                          + " 		-o-border-radius: 10px; \n"
                          + " 		border-radius: 10px; \n"
                          + "       -moz-box-shadow: 0px 5px 5px #777; \n"
                          + "		-webkit-box-shadow: 0px 5px 5px #777; \n"
                          + "		box-shadow: 0px 5px 5px #777; \n"
                          + "       background: #FFFFFF; \n"
                          + "   }\n"
                          + "	.itemTitle{ \n"
                          + "		padding-top:30px;\n"
                          + " 	} \n"
                          + " 	#container .selectedItem{ \n"
                          + " 		-moz-box-shadow: 0 4px 10px #FFFFFF; \n"
                          + " 		-webkit-box-shadow: 0 4px 10px #FFFFFF; \n"
                          + " 		box-shadow: 0 4px 10px #FFFFFF; \n"
                          + " 		border:1px solid #FFFFFF; \n"
                          + "       background: #FFFFFF; \n"
                          + "	} \n"
                          + "   #container2{ \n"
                          + " 		/*border:1px solid magenta;*/ \n"
                          + " 		width:850px; \n"
                          + "		height:200px; \n"
                          + " 		margin-left:25px; \n"
                          + "	} \n"
                          + "	#container2 img, #container2 .item{ \n"
                          + "		width:100%; \n"
                          + " 		height:100%; \n"
                          + " 		-webkit-border-radius: 10px; \n"
                          + "   	-moz-border-radius: 10px; \n"
                          + " 		-o-border-radius: 10px; \n"
                          + " 		border-radius: 10px; \n"
                          + " 		-moz-box-shadow: 0px 5px 5px #777; \n"
                          + "		-webkit-box-shadow: 0px 5px 5px #777; \n"
                          + "		box-shadow: 0px 5px 5px #777; \n"
                          + "	} \n"
                          + "	/*#container2 .selectedItem{ \n"
                          + " 		border:2px solid #0071BC; \n"
                          + "	}*/ \n"
                          + "</style>\n";

                SyndicationFeed rssData = SyndicationFeed.Load(reader);
                aux = rssData.Items.ElementAt(0).Links.ElementAt(0).Uri.Query.IndexOf('&');
                codigo = rssData.Items.ElementAt(0).Links.ElementAt(0).Uri.Query.Substring(3, aux -3 );
                ret = ret + "<div> \n"
		                  + "<iframe id=\"rep\" name=\"rep\" src=\"http://www.youtube.com/embed/" + codigo + "\" width=\""+ width.ToString() + "\" height=\"" + height.ToString() + "\"  frameborder=\"0\"></iframe> \n"
                	      + "</div> \n"
	                      + "<div id=\"container\"> \n";
                for (int i = 0; (i < cant) && (i < rssData.Items.Count()); i++)
                {
                    aux = rssData.Items.ElementAt(i).Links.ElementAt(0).Uri.Query.LastIndexOf('&');
                    codigo = rssData.Items.ElementAt(i).Links.ElementAt(0).Uri.Query.Substring(3, aux - 3);
                    ret = ret + "<img id=\"" + codigo + "\" src=\"http://img.youtube.com/vi/" + codigo + "/default.jpg\" title=\"" + rssData.Items.ElementAt(i).Title.Text + "\" /> \n";
                }

                ret = ret + "</div> \n"
                          + "<script> \n"
                          + "	$('#container').coverscroll(); \n"
                          + "	$('#container').dblclick(function(){ \n"
                          + "		var valor = $(\".selectedItem\").attr('id') \n"
                          + "		var dato = \"http://www.youtube.com/embed/\" + valor; \n"
                          + "		var iframe = $('#rep')[0]; \n"
                          + "		iframe.src = dato; \n"
                          + "	}); \n"
                          + "</script>	 \n";
                          //+ "<Style> \n"
                          //+ "	#container{ \n"
                          //+ "		height:" + (height ).ToString() + "px; \n"
                          //+ "</Style> \n";
                return ret;
            }
        }

        public static string RSSFeed(string nombre,int cantVisualizar, bool showDescription, string searchTag, IList<SyndicationItem> items)
        {
            string title = "<h2>" + nombre + "</h2>";
            string itemStr = "";
            try
            {
                if (items != null)
                {
                    IList<SyndicationItem> itemsRecorrida = new List<SyndicationItem>();
                    int cant = 0;
                    foreach (SyndicationItem i in items)
                    {
                        if (( ((i.Summary != null) && (i.Summary.Text.Contains(searchTag.Trim())))
                             || i.Title.Text.Contains(searchTag.Trim())
                             || (searchTag.Trim() == ""))
                                && (cant < cantVisualizar))
                        {
                            cant++;
                            string URL = i.Links[0].Uri.OriginalString;
                            string Title = i.Title.Text;
                            itemStr = itemStr + string.Format("<p><a href=\"{0}\"><b>{1}</b></a>", URL, Title) + "<br/>";
                            if (showDescription && (i.Summary != null))
                                itemStr = itemStr + i.Summary.Text + "</p>";
                        }
                    }
                    foreach (SyndicationItem item in itemsRecorrida)
                    {

                    }
                }
            }
            catch (Exception e)
            {
            }
            if (itemStr == "")
                itemStr = "There are no items that match the search tag or the service is not available.";
            return title + itemStr;
        }
    }
}